package com.overtime.application.service.impl;

import com.base.bean.RespBean;
import com.common.UserUtils;
import com.overtime.application.bean.Application;
import com.overtime.application.bean.ApplicationResult;
import com.overtime.application.mapper.ApplicationMapper;
import com.overtime.application.mapper.ApplicationResultMapper;
import com.overtime.application.service.ApplicationResultService;
import com.overtime.application.service.ApplicationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by renxin on 2018/8/16 0016.
 */
@Service
@Transactional
public class ApplicationServiceImpl implements ApplicationService {
    @Autowired
    private ApplicationMapper applicationMapper;
    @Autowired
    private ApplicationResultMapper applicationResultMapper;

    @Override
    public Map<String,Object> query(Application application,int page_num,int page_size, String overtime_all_time) throws Exception {
        //String[] strings = map.get("over_all_time");
        if(!("".equals(overtime_all_time)||"null".equals(overtime_all_time))){
            String[] strings = overtime_all_time.split(",");
            //转换时间  将String转换为Date
            if(!("".equals(strings[0]))){
                application.setApplication_start_time(parseHour(strings[0]));
                application.setApplication_end_time(parseHour(strings[1]));
            }
        }
        Map map = new HashMap<String,Object>();
        //指定分页的页码
        page_num = (page_num-1)*page_size;
        List<Map<String, Object>> list = applicationMapper.query(application, page_num, page_size);
        int totalSize = applicationMapper.queryTotalSize(application);
        map.put("pageData",list);
        map.put("total",totalSize);
        return map;
    }

    @Override
    public List<Map<String, Object>> queryDepartment() throws Exception {
        List<Map<String,Object>> list = applicationMapper.queryDepartment();
        return list;
    }

    @Override
    public RespBean applicationSave(Application application, String overtime_all_time, HttpServletRequest request) throws Exception {
        RespBean respBean = new RespBean();
        Date start_time = null;
        Date end_time = null;
        try {
            List<String> timelist =getMonthLastDate(overtime_all_time);
            for(String overtime_time:timelist){
                int workDays=0;
                int weekend = 0;
                int holiday=0;
                //以逗号分隔，获取开始时间和结束时间
                if(!("".equals(overtime_time))){
                    String[] strings = overtime_time.split(",");

                    //转换为日期,设置开始和结束时间
                    start_time = parseHour(strings[0]);
                    end_time = parseHour(strings[1]);
                    Calendar calendar = Calendar.getInstance();
                    Calendar calendar1 = Calendar.getInstance();
                    calendar.setTime(parseHour(strings[0]));
                    calendar1.setTime(parseHour(strings[1]));
                    Date start = calendar.getTime();
                    Date end = calendar1.getTime();
                    while (start.getTime()<=end.getTime()){
                        Map map = new HashMap();
                        map.put("time",start);
                        List<Map> list = applicationMapper.getTime(map);
                        if(calendar.get(Calendar.DAY_OF_WEEK)!=7&&calendar.get(Calendar.DAY_OF_WEEK)!=1){
                            if(list.size()==0){
                                workDays++;
                            }else {
                                holiday++;
                            }
                        }else {
                            if(list.size()>0){
                                if((int)list.get(0).get("type")==0)
                                    holiday++;
                                else
                                    workDays++;
                            }else{
                                weekend++;
                            }
                        }
                        calendar.add(Calendar.DAY_OF_MONTH,1);
                        start = calendar.getTime();
                    }
                }
                String account_time = "工作日:"+workDays+",节假日:"+holiday+",周末:"+weekend;
                int day = workDays + holiday + weekend;
                application.setAccout_time(account_time);
                if((workDays+holiday+weekend)>10){
                    List<Map> list = queryAL(2);
                    int audit_level_id = 2;
                    application.setAudit_level_id(audit_level_id);
                    //设置审核状态
                    application.setApplication_status(3);
                }else{
                    List<Map> list = queryAL(1);
                    int audit_level_id = 1;
                    application.setAudit_level_id(audit_level_id);
                    //设置审核状态
                    application.setApplication_status(3);
                }
                //设置申请时间
                application.setApplication_time(new Date());
                application.setApplication_type(0);
                application.setApplication_start_time(start_time);
                application.setApplication_end_time(end_time);
                List<Application> applicationList = applicationMapper.queryApplicationByUserIdTime(application);
                if(!ObjectUtils.isEmpty(applicationList)){
                    respBean.setStatus("error");
                    respBean.setMsg("新增失败，同一时间段已有加班申请");
                    return respBean;
                }
                applicationMapper.applicationSave(application);
                //新增一个加班申请单就会新增一个加班结果表
                ApplicationResult applicationResult = new ApplicationResult();
                applicationResult.setApplication_id(application.getApplication_id());
                applicationResult.setResult_status(2);
                applicationResult.setIs_result_fee(1);
                applicationResult.setResult_time_day(day);
                applicationResult.setResult_start_time(start_time);
                applicationResult.setResult_end_time(end_time);
                applicationResultMapper.saveApplicaitonResult(applicationResult);
            }
            respBean.setStatus("success");
            respBean.setMsg("新增成功");
        }catch (Exception e){
            respBean.setStatus("error");
            respBean.setMsg("出错了，请联系管理员");
            e.printStackTrace();
        }
        return respBean;
    }

    @Override
    public List<Map<String, Object>> queryUser(int depno) throws Exception {
        List<Map<String,Object>> list = applicationMapper.queryUser(depno);
        return list;
    }

    @Override
    public RespBean delApplication(String[] ids) throws Exception {
        RespBean respBean = new RespBean();
        try {
            Map map = new HashMap();
            map.put("user_id",UserUtils.getCurrentHr().getId());
            map.put("depno",UserUtils.getCurrentHr().getDepartmentId());
            if(!("".equals(ids[0]))){
                for (int i = 0;i < ids.length;i++){
                    map.put("id",ids[i]);
                    List<Map<String, Object>> list = applicationMapper.queryById(map);
                    Map map1 = list.get(0);
                    if((Integer)map1.get("application_status")!=2){
                        ApplicationResult applicationResult = applicationResultMapper.getKey(Integer.parseInt(ids[i]));
                        applicationResultMapper.delApplicationResult(applicationResult.getResult_id());
                        applicationMapper.delApplication(Integer.parseInt(ids[i]));
                    }

                }
            }
            respBean.setStatus("success");
            respBean.setMsg("删除成功");
        }catch (Exception e){
            respBean.setMsg("删除出错,请联系管理员");
            respBean.setStatus("error");
            e.printStackTrace();
        }
        return respBean;
    }

    @Override
    public List<Map<String, Object>> queryById(String application_id) throws Exception{
        Integer id = Integer.parseInt(application_id);
        long user_id= UserUtils.getCurrentHr().getId();
        long depno = UserUtils.getCurrentHr().getDepartmentId();
        Map map = new HashMap();
        map.put("id",id);
        map.put("user_id",user_id);
        map.put("depno",depno);
        List<Map<String,Object>> list = applicationMapper.queryById(map);
        return list;
    }

    @Override
    public RespBean applicationEdit(Application application, String overtime_all_time) throws Exception {
        RespBean respBean = new RespBean();
        int workDays=0;
        int weekend = 0;
        int holiday=0;
        try {
            if(!("".equals(overtime_all_time))){
                String[] strings = overtime_all_time.split(",");
                //转换为日期,设置开始和结束时间
                application.setApplication_start_time(parseHour(strings[0]));
                application.setApplication_end_time(parseHour(strings[1]));
                Calendar calendar = Calendar.getInstance();
                Calendar calendar1 = Calendar.getInstance();
                calendar.setTime(parseHour(strings[0]));
                calendar1.setTime(parseHour(strings[1]));
                Date start = calendar.getTime();
                Date end = calendar1.getTime();
                while (start.getTime()<end.getTime()){
                    Map map = new HashMap();
                    map.put("time",start);
                    List list = applicationMapper.getTime(map);
                    if(calendar.get(Calendar.DAY_OF_WEEK)!=7&&calendar.get(Calendar.DAY_OF_WEEK)!=1){
                        if(list.size()==0){
                            workDays++;
                        }else {
                            holiday++;
                        }
                    }else {
                        if(list.size()>0){
                            workDays++;
                        }else{
                            weekend++;
                        }
                    }
                    calendar.add(Calendar.DAY_OF_MONTH,1);
                    start = calendar.getTime();
                }
            }
            if(application.getApplication_status() == 4){
                application.setApplication_status(1);
            }
            application.setApplication_time(new Date());
            List<Application> applicationList = applicationMapper.queryApplicationByUserIdTime(application);
            if(!ObjectUtils.isEmpty(applicationList)){
                respBean.setStatus("error");
                respBean.setMsg("新增失败，同一时间段已有加班申请");
                return respBean;
            }
            applicationMapper.applicationEdit(application);
            respBean.setStatus("success");
            respBean.setMsg("修改保存成功");
        }catch (Exception e){
            respBean.setStatus("error");
            respBean.setMsg("修改出错，请联系管理员");
            e.printStackTrace();
        }
        return respBean;
    }

    @Override
    public List<Map<String, Object>> queryProject() throws Exception {
        return applicationMapper.queryProject();
    }


    /**转换时间方法
     * @param datdString "Tue Jul 12 12:10:11 GMT+08:00 2016";
     * @return 时分秒
     */
    public static Date parseHour(String datdString) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(datdString, pos);
        //Date date = new Date(datdString);
        return strtodate;
    }
    @Override
    public List queryAL(int al){
        Map map = new HashMap();
        map.put("al",al);
        return applicationMapper.queryAL(map);
    }

    public static List<String> getMonthLastDate(String date){
        List<String> list =new ArrayList<>();
        String[] strings = date.split(",");
        if(!strings[0].substring(5,7).equals(strings[1].substring(5,7))){
            int year = Integer.parseInt(strings[0].split("-")[0]);  //年
            int month = Integer.parseInt(strings[0].split("-")[1]); //月
            Calendar cal = Calendar.getInstance();
            // 设置年份
            cal.set(Calendar.YEAR, year);
            // 设置月份
            // cal.set(Calendar.MONTH, month - 1);
            cal.set(Calendar.MONTH, month); //设置当前月的上一个月
            // 获取某月最大天数
            //int lastDay = cal.getActualMaximum(Calendar.DATE);
            int lastDay = cal.getMinimum(Calendar.DATE); //获取月份中的最小值，即第一天
            // 设置日历中月份的最大天数
            //cal.set(Calendar.DAY_OF_MONTH, lastDay);
            cal.set(Calendar.DAY_OF_MONTH, lastDay - 1); //上月的第一天减去1就是当月的最后一天
            // 格式化日期
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String endTime=sdf.format(cal.getTime());
            list.add(strings[0]+","+endTime);

            String  secondStartDate = strings[1].substring(0,8)+"01";
            list.add(secondStartDate+","+strings[1]);

        }else{
            list.add(date);
        }
        return list;
    }
}
